package dwSvrPub

import (
	"encoding/xml"
	"fmt"
	"os"
	"time"

	"path/filepath"

	"gitee.com/wchpub/fnsvr"
	"gitee.com/wchpub/fnsvr/ysEntry"
)

// 服务器配置
type serverConfig struct {

	//游戏版本号，3位，客户端是4位
	Version string `xml:"version"`

	//时区
	Location string `xml:"location"`

	// 是否开发模式
	IsDev bool `xml:"isDev"`

	// 日志路径
	LogPath string `xml:"logPath"`

	// 可信任代理
	TrustedProxies []string `xml:"trustedProxies>proxy"`

	// game服务端口
	GamePort int `xml:"gamePort"`

	// 登录服务端口
	LgPort int `xml:"lgPort"`

	// 世界诞生时间 "2025-08-06"
	WorldBirthTime string `xml:"worldBirthTime"`

	//有效的iso地区代码 cn
	IsoCodes string `xml:"isoCodes"`
}

type isoCodeList map[string]struct{}

// 有效的iso地区代码
var IsoCodes map[string]isoCodeList

// 抖小配置
/*
type dyMiniConfig struct {
	AppId     string `xml:"appId"`
	AppSecret string `xml:"appSecret"`
}*/

// 服务器配置
type DwGameConfig struct {

	// 服务器配置
	ServerConfig serverConfig `xml:"server"`

	// mongodb
	MongodbConfig fnsvr.MongoDbConfig `xml:"mongodb"`

	// redis配置
	RedisConfig fnsvr.RedisConfig `xml:"redis"`

	// oss配置
	OssConfig fnsvr.OssConfig `xml:"oss"`

	// YsEntry
	YsEntryConfig ysEntry.YsEntryConfig `xml:"ysEntry"`
}

var GameConfig *DwGameConfig
var SvrSpace string //服务空间

var Location *time.Location //时区
// 世界诞生时间
var WorldBirthTime time.Time

// 读取配置
func LoadConfig() error {

	SvrSpace = fnsvr.Getenv("SVR_SPACE", "dev")

	//初始化地区iso代号
	cnIsoList := []string{
		"BJ", "TJ", "HE", "SX", "NM",
		"LN", "JL", "HL", "SH", "JS",
		"ZJ", "AH", "FJ", "JX", "SD",
		"HA", "HB", "HN", "GD", "GX",
		"HI", "CQ", "SC", "GZ", "YN",
		"XZ", "SN", "GS", "QH", "NX",
		"XJ", "TW", "HK", "MO",
	}

	cnIso := make(isoCodeList)
	for _, code := range cnIsoList {
		cnIso[code] = struct{}{}
	}

	IsoCodes = make(map[string]isoCodeList)
	IsoCodes["cn"] = cnIso

	xmlFilePath, err := configPath()
	if err != nil {
		return err
	}
	cfg, err := readXMLFile(xmlFilePath)
	if err != nil {
		return err
	}
	GameConfig = cfg

	//检查iso代号配置
	_, isok := IsoCodes[cfg.ServerConfig.IsoCodes]
	if !isok {
		return fmt.Errorf("non-existent iso codes %s", cfg.ServerConfig.IsoCodes)
	}

	if cfg.ServerConfig.Location == "" {
		return fmt.Errorf("load cfg err location is empty")
	}

	//初始化时区
	Location, err = time.LoadLocation(cfg.ServerConfig.Location)
	if err != nil {
		return err
	}

	//解析世界诞生时间
	timeObj, err := time.ParseInLocation("2006-01-02", cfg.ServerConfig.WorldBirthTime, Location)
	if err != nil {
		return err
	}
	WorldBirthTime = timeObj.UTC()

	return nil
}

func configPath() (string, error) {

	rootDir, err := ConfigRoot()
	if err != nil {
		return "", err
	}

	return filepath.Join(rootDir, "bigWordSvr.xml"), nil
}

// 配置文件跟路径
func ConfigRoot() (string, error) {
	homeDir, err := os.UserHomeDir()
	if err != nil {
		return "", err
	}

	defaultPath := filepath.Join(homeDir, "svrcfg")
	configPath := fnsvr.Getenv("SVR_CONFIG_PATH", defaultPath)

	return filepath.Join(configPath, SvrSpace), nil
}

// 配置表路径
func TablePath() (string, error) {

	rootDir, err := ConfigRoot()
	if err != nil {
		return "", err
	}

	return filepath.Join(rootDir, "dwCfgs"), nil
}

// 读取xml文件
func readXMLFile(filename string) (*DwGameConfig, error) {
	data, err := os.ReadFile(filename)

	if err != nil {
		return nil, err
	}

	var config DwGameConfig
	err = xml.Unmarshal(data, &config)
	if err != nil {
		return nil, err
	}

	return &config, nil
}
